package cn.car.service.impl;

import cn.car.constants.CarAccessConstants;
import cn.car.domains.entity.CameraSnapshotEntity;
import cn.car.mapper.CameraSnapshotMapper;
import cn.car.service.CameraSnapshotService;
import cn.car.utils.Base64ToImageUtil;
import cn.hutool.core.collection.CollectionUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.function.Supplier;

@Service
@Slf4j
public class CameraSnapshotServiceImpl implements CameraSnapshotService {

    private static final Supplier<String> IMAGE_DIRECTORY = () -> String.join(File.separator, CarAccessConstants.getPictureFilePath().get(), "cameraSnapshot");

    @Resource
    private CameraSnapshotMapper cameraSnapshotMapper;

    @Override
    public void storeImage(String ip, String imageFile) {


        final String fileName = System.currentTimeMillis() + ".jpeg";
        final String fileDir = String.join(File.separator, IMAGE_DIRECTORY.get(), ip);
        final String filePath = String.join(File.separator, fileDir, fileName);

        // 确保目录存在
        final File directory = new File(fileDir);
        if (!directory.exists()) {
            final boolean hasMake = directory.mkdirs();
            log.trace("[CAMERA_SNAP] storeImage, Create directory, result: {}, path:{}", hasMake, directory.getAbsolutePath());
        }
        try {
            Base64ToImageUtil.saveBase64ImageToFile(imageFile, filePath);
            log.trace("[CAMERA_SNAP] storeImage, Save imageFile to local: {}", filePath);
        } catch (IOException e) {
            log.error("[CAMERA_SNAP] Save imageFile error cameraIp:{} e", ip, e);
        }


        // 存储元数据到数据库
        final CameraSnapshotEntity snapshot = new CameraSnapshotEntity();
        snapshot.setCameraIp(ip);
        snapshot.setSnapshotTime(new Date());
        snapshot.setSnapshotPath(filePath);
        this.insert(snapshot);
        log.trace("[CAMERA_SNAP] storeImage, Save imageMeta to database: {}", snapshot);

    }

    @Override
    public void insert(CameraSnapshotEntity cameraSnapshotEntity) {
        cameraSnapshotMapper.insert(cameraSnapshotEntity);
    }

    @Override
    public List<Long> selectBeforeDate(Date offset) {
        return cameraSnapshotMapper.selectBeforeDate(offset);
    }

    @Override
    public void deleteImage(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return;
        }
        cameraSnapshotMapper.deleteImage(ids);
    }

    @Override
    public CameraSnapshotEntity getLastSnapshot(String cameraIp, Date date) {
        return cameraSnapshotMapper.getLastSnapshot(cameraIp, date);
    }
}
